<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <areas-tree ref="tree" :areas="treeAreas" v-on:handleNodeClick="onHandleNodeClick"/>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-card>
          <div class="filter-container">

            <el-button v-if="checkPermission('添加区域')" class="filter-item" icon="el-icon-location" style="margin-left: 20px"
                       type="primary" @click="createArea(1)">
              新建小区
            </el-button>
            <el-button v-if="list.length > 0 && checkPermission('添加区域')" class="filter-item" icon="el-icon-office-building"
                       style="margin-left: 20px" type="primary" @click="createArea(2)">
              新建楼栋
            </el-button>
          </div>
          <div class="app-container">
            <el-table
              :key="tableKey"
              v-loading="listLoading"
              :cell-style="{padding:0+'px'}"
              :data="list"
              :row-style="{height:40+'px'}"
              border
              fit
              highlight-current-row
              style="width: 100%;"
            >
              <el-table-column
                type="index"
                width="50">
              </el-table-column>
              <el-table-column align="left" label="区域编码" width="120">
                <template slot-scope="{row}">
                  <span>{{ row.code }}</span>
                </template>
              </el-table-column>
              <el-table-column align="left" label="类型" width="60">
                <template slot-scope="{row}">
                  <span>{{ formatType(row.type) }}</span>
                </template>
              </el-table-column>
              <el-table-column align="left" label="地址">
                <template slot-scope="{row}">
                  <router-link to="/gis/index">
                    <el-link type="info">{{ row.address }}</el-link>
                  </router-link>
                </template>
              </el-table-column>
              <el-table-column align="left" label="添加时间">
                <template slot-scope="{row}">
                  <span>{{ formatDate(row.create_time) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="备注">
                <template slot-scope="{row}">
                  <span>{{ row.remark }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="230">
                <template slot-scope="{row,$index}">
                  <el-button v-if="checkPermission('删除区域')" circle icon="el-icon-delete" type="danger"
                             @click="handleDelete(row,$index)">
                  </el-button>
                  <el-button v-if="checkPermission('修改区域')" circle icon="el-icon-edit" type="primary"
                             @click="updateArea(row)">
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total>0" :limit.sync="listQuery.pageSize" :page.sync="listQuery.page" :total="total"
                        @pagination="getList"/>

            <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible"
                       custom-class="window-small-width">
              <el-form ref="dataForm" :model="temp" :rules="rules" label-position="right" label-width="70px">
                <el-form-item label="所属区域" label-width="80px" prop="area">
                  <area-selector ref="areaSelector" :areas="selectorAreas" :disable="dialogStatus=='update'"
                                 :value="temp.path" v-on:selectArea="onSelectArea"></area-selector>
                </el-form-item>
                <el-form-item label="名称" label-width="80px" prop="name">
                  <el-input v-model="temp.name"/>
                </el-form-item>
                <el-form-item label="备注" label-width="80px" prop="remark">
                  <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入"
                            type="textarea"/>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                  取消
                </el-button>
                <el-button :loading="submitLoading" type="primary"
                           @click="dialogStatus == 'create' ? handleCreate():handleUpdate()">
                  确认
                </el-button>
              </div>
            </el-dialog>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import areasTree from '@/components/area/AreaTree'
import AreaSelector from '@/components/area/AreaSelector'
import Pagination from '@/components/Pagination'
import {areas} from "@/utils/areas"
import {checkPermission} from "@/utils/permission"
import {addArea, deleteArea, getAreaList, getAreaTree, updateArea} from "@/api/area";

export default {
  name: 'AreaList',
  components: {AreaSelector, areasTree, Pagination},
  data() {
    const validateArea = (rule, value, callback) => {
      if (this.temp.code === '') {
        callback(new Error('请选择区域'))
      } else {
        callback()
      }
    }
    return {
      dialogFormVisible: false,
      dialogStatus: 'create',
      tableKey: 0,
      listLoading: true,
      submitLoading: false,
      list: [],
      treeAreas: [],
      selectorAreas: areas,
      temp: {
        id: '',
        code: '',
        path: [],
        type: 1,
        address: '',
        remark: ''
      },
      areaType: 1,
      total: 0,
      textMap: {
        update: '编辑区域',
        create: '新建区域'
      },
      listQuery: {
        id: 0,
        page: 1,
        pageSize: 20,
        name: ''
      },
      rules: {
        name: [{required: true, message: '名称必填', trigger: 'blur'}],
        community: [{required: true, message: '请选择小区', trigger: 'change'}],
        area: [{validator: validateArea, required: true, trigger: 'change'}]
      }
    }
  },
  created() {
    this.getList()
    this.getAreaTree()
  },
  methods: {
    checkPermission,
    onHandleNodeClick: function (data) {
      if (this.listQuery.code !== data.code) {
        this.listQuery.code = data.code
        this.getList()
      }
    },
    getAreaTree(type) {
      getAreaTree({type: 1}).then(response => {
        this.treeAreas = response.data
      })
    },
    getList() {
      this.listLoading = true
      getAreaList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    createArea(type) {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      if (type === 1) {
        this.selectorAreas = Object.assign([], areas)
      } else {
        this.selectorAreas = Object.assign([], this.treeAreas)
      }
      this.temp.type = type
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateArea(row) {
      this.resetTemp()
      this.dialogStatus = 'update'
      this.temp = Object.assign({}, row)
      this.temp.path = this.temp.path.split(',')
      this.temp.path.pop()
      this.dialogFormVisible = true
      if (row.type === 1) {
        this.selectorAreas = Object.assign([], areas)
      } else {
        this.selectorAreas = Object.assign([], this.treeAreas)
      }
      this.$nextTick(() => {//等待子组件mount再执行
        //this.$refs['areaSelector'].setSelectedNodes(this.temp.path)
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateArea(tempData).then(response => {
            if (response.code === 20000) {
              this.$notify({
                title: 'Success',
                message: '更新成功',
                type: 'success',
                duration: 3000
              })
              this.getList()
              this.getAreaTree()
            } else {
              this.$notify({
                title: 'Failed',
                message: '更新失败',
                type: 'error',
                duration: 3000
              })
            }
          })
        }
      })
    },
    handleCreate() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.submitLoading = true
          const tempData = Object.assign({}, this.temp)
          addArea(tempData).then(response => {
            const {code, message} = response
            if (code === 20000) {
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: '添加成功',
                type: 'success',
                duration: 3000
              })
              this.getList()
              this.getAreaTree()
            } else {
              this.$notify({
                title: 'Failed',
                message: message,
                type: 'success',
                duration: 3000
              })
            }
          })
          this.submitLoading = false
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该区域, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteArea(row).then(response => {
          if (response.code === 20000) {
            this.$notify({
              title: 'Success',
              message: '成功删除',
              type: 'success',
              duration: 3000
            })
            this.getList()
            this.getAreaTree()
          } else {
            this.$notify({
              title: 'Failed',
              message: '无法删除',
              type: 'error',
              duration: 3000
            })
          }
        })
      })
    },
    onSelectArea(data) {
      if (data !== '') {
        this.temp.path = data.path
        this.temp.code = data.value
        this.temp.address = data.pathLabels.join('/')
      } else {
        this.temp.code = ''
      }
    },
    formatType(type) {
      if (type === 1) {
        return "小区"
      }
      return "楼栋"
    },
    formatDate(dateStr) {
      const d = new Date(dateStr)
      if (d.getMilliseconds() === 0) {
        return '-'
      }
      return d.toLocaleDateString()
    },
    resetTemp() {
      this.temp = {
        code: '',
        address: '',
        area: '',
        path: [],
        type: 1, // 0 小区 1楼栋
        name: '',
        remark: ''
      }
    },
    resetQueryParams() {
      this.listQuery = {
        id: 0,
        page: 1,
        pageSize: 20,
        name: ''
      }
    }
  }
}
</script>
